import React, {Component} from "react";
import {bindActionCreators} from "redux";
import {Icon, Modal, Card, Tooltip, message, Button} from "antd";
import { CopyToClipboard } from 'react-copy-to-clipboard';
import {connect} from "react-redux";
import SearchList from "./SearchList/SearchList";
import DetailModal from './DetailModal/DetailModal';
import OrderProcessModal from './DetailModal/OrderProcessModal';
import ReviewProcessModal from './DetailModal/ReviewProcessModal';
import AuthModal from './AuthModal/AuthModal';
import {CommonTable} from "components";
import {axios, orderStatus} from "utils";
import {orderListAction} from "./index";
import moment from "moment/moment";
import download from 'downloadjs';
import styles from './OrderList.less';

class OrderList extends Component {
    modalTableColumns = [
        {
            title: "分数",
            dataIndex: "score",
            key: "score"
        },
        {
            title: "决策",
            dataIndex: "decision",
            key: "decision"
        },
        {
            title: "风险名称",
            dataIndex: "risk_name",
            key: "risk_name"
        }
    ];

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            modalData: null,
            detailVisible: false,
            btnDisabled: false,
            orderProcessVisible:false,
            reviewProcessVisible:false
        };
        this.pageSize = 10;
        this.searchStatus = {};
        //判断是否点击手动机审按钮
        this.isHasClick = false;
        const _this = this;
        //当前的记录
        this.currentRecord = null;

        this.columns = [
            {
                title: "订单号",
                dataIndex: "orderNo",
                key: "orderNo",
                render(text) {
                    return (
                        <CopyToClipboard text={text} onCopy={_this.onCopy}>
                            <Tooltip title={'点击复制'}>
                                <span style={{cursor: 'pointer'}}>{text}</span>
                            </Tooltip>
                        </CopyToClipboard>
                    );

                }
            },
            {
                title: "姓名",
                dataIndex: "userTrueName",
                key: "userTrueName",
                render(text) {
                    return (
                        <CopyToClipboard text={text} onCopy={_this.onCopy}>
                            <Tooltip title={'点击复制'}>
                                <span style={{cursor: 'pointer'}}>{text}</span>
                            </Tooltip>
                        </CopyToClipboard>
                    );
                }
            },
            {
                title: "手机号",
                dataIndex: "userPhone",
                key: "userPhone",
                render(text) {
                    return (
                        <CopyToClipboard text={text} onCopy={_this.onCopy}>
                            <Tooltip title={'点击复制'}>
                                <span style={{cursor: 'pointer'}}>{text}</span>
                            </Tooltip>
                        </CopyToClipboard>
                    );
                }
            },
            {
                title: "是否是老用户",
                dataIndex: "isOlduser",
                key: "isOlduser",
                width: '80px',
                render(text) {
                    return Number(text) === 0 ? "否" : "是";
                }
            },
            {title: '正常还款金额(元)', dataIndex: 'deviceMoney', key: 'deviceMoney'},
            {title: "申请金额(元)", dataIndex: "lendMoney", key: "lendMoney"},
            {title: "借款期限(天)", dataIndex: "lendDays", key: "lendDays"},
            {
                title: "手续费(元)",
                dataIndex: "serviceMoney",
                key: "serviceMoney",
                render(text, record) {
                    const {deviceMoney, lendMoney } = record;
                    const res = (Number(deviceMoney)*10) - (Number(lendMoney)*10);
                    const resNum = res/10
                    // return Number.isInteger(res) ? res : res.toFixed(2);
                    return resNum;
                }
            },
            {
                title: "申请时间",
                dataIndex: "applyTime",
                key: "applyTime",
                render(text) {
                    return moment(Number(text) * 1000).format("YYYY-MM-DD HH:mm:ss");
                }
            },
            {
                title: '放款时间',
                dataIndex: 'loanTime',
                key: 'loanTime',
                render(text) {
                    const time = Number(text);
                    if(!time) {
                        return '无';
                    }
                    return moment(text * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            {
                title: '到期时间',
                dataIndex: 'expireTime',
                key: 'expireTime',
                render(text) {
                    const time = Number(text);
                    if(!time) {
                        return '无';
                    }
                    return moment(text * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            {title: "渠道来源", dataIndex: "channelId", key: "channelId"},
            {
                title: "审核员",
                dataIndex: "examiner2Name",
                key: "examiner2Name",
                width:'120px',
                render(text, record) {
                    const { examiner3Name } = record;
                    let ele = [];
                    if(text) {
                        ele.push(<div key={1}>复审：{text}</div>);
                    }
                    if(examiner3Name) {
                        ele.push(<div>终审：{examiner3Name}</div>);
                    }
                    return (
                        <div>
                            {ele}
                        </div>
                    );
                }
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                render(text) {
                    return orderStatus[text];
                }
            },
            {
                title: '操作',
                dataIndex: 'id',
                key: 'id',
                width: 135,
                render(text, record) {
                    let { status } = record;
                    status = Number(status);
                    let ele = [];
                    if(status === 4 || status === 7) {
                        ele.push(
                            <Tooltip key={1} title={'查看被拒原因'}>
                                <div className={styles.item} onClick={() => _this.handleClickDetail(record)}><Icon type={"file"}/></div>
                            </Tooltip>
                        );
                    }
                    if(status === 1) {
                        ele.push(
                            <Tooltip key={2} title={'查看认证信息'}>
                                <div className={styles.item} onClick={() =>_this.lookAuthInfo(record)}><Icon type="exclamation-circle-o" /></div>
                            </Tooltip>
                        )
                    }

                    return (
                        <div className={styles.operatorWrapper}>
                        {
                            <Tooltip key={3} title={'查看订单详情'}>
                                <div onClick={() => _this.showDetailModal(record)} className={styles.item}><Icon type={"user"}/></div>
                            </Tooltip>
                        }
                        {
                            <Tooltip key={4} title={'查询订单进度'}>
                                <div onClick={() => _this.orderProcess(record)} className={styles.item}><Icon type={"file-text"}/></div>
                            </Tooltip>
                        }
                        {
                            <Tooltip key={5} title={'查询审核进度'}>
                                <div onClick={() => _this.reviewProcess(record)} className={styles.item}><Icon type={"file-unknown"}/></div>
                            </Tooltip>
                        }
                        {ele}
                        {/* {
                            <Tooltip key={4} title={'测试按钮'}>
                                <div onClick={() => _this.showApprovalFlow(record)} className={styles.item}><Icon type={'file'}/></div>
                            </Tooltip>
                        } */}
                        </div>

                    );


                }
            }
        ];
    }
    onCopy = () => {
        message.success('复制成功', 2);
    }

    //查看认证信息
    lookAuthInfo = (record) => {
        this.currentRecord = record;
        const { orderNo } = record;
        const { getAuthData } = this.props;
        getAuthData({ orderNo });
    }
    handleClickDetail = record => {
        const {id} = record;
        const _this = this;
        this.setState({ visible: true });
        axios
            .post("/hs/admin/orderReview/getOrderInfo", {orderId: id})
            .then(res => {
                if (Number(res.code) === 200) {
                    const {data: { refundReason }} = res;
                    let item;
                    if (refundReason) {
                        try {
                            //同盾被拒
                            const obj = JSON.parse(refundReason)
                            item = obj['risk_items'];
                        } catch (e) {
                            //运营商被拒或者审核时被拒
                            item = refundReason;
                        }
                    }
                    _this.setState({ modalData: item });
                }
            });
    };

    //todo 手动机审
    manualCheck = () => {
        const { id } = this.currentRecord;
        const { getTableData, tableData: {pagination = {current: 1}}, changeAuthModal } = this.props;
        const _this = this;
        let hide = null;
        if(!this.isHasClick) {
            this.isHasClick = true;
            hide = message.loading('正在进行机审,请勿重复操作！', 0);
            axios
                .post('/hs/admin/orderReview/submitMachineReview', { orderId: id })
                .then(res => {
                    hide && hide();
                    //关闭弹框
                    changeAuthModal(false);
                    if(Number(res.code) === 200) {
                        message.success('操作成功');
                        //刷新数据
                        const params = {
                            // status: this.searchStatus,
                            ...this.searchStatus,
                            pageNum: pagination["current"],
                            pageSize: this.pageSize
                        };
                        getTableData(params);
                    }
                    _this.isHasClick = false;
                })
                .catch(() => {
                    hide && hide();
                    _this.isHasClick = false;
                })
        }

    }

    handlePageChange = info => {
        const {current, pageSize} = info;
        const {getTableData} = this.props;
        getTableData({pageNum: current, pageSize, ...this.searchStatus});
    };

    handleOk = () => {
        this.setState({visible: false, modalData: []});
    };
    handleCancel = () => {
        this.setState({visible: false}, () => {
            this.setState({
                modalData: null
            })
        });
    };

    handleSearch = obj => {
        const { getTableData } = this.props;
        const { time } = obj;
        const isArr = Array.isArray(time) && time.length > 0;
        const params = {
            ...obj,
            yStartTime: isArr ? time[0].format('YYYY-MM-DD 00:00:00') : '',
            yEndTime: isArr ? time[1].format('YYYY-MM-DD 23:59:59') : '',
        };
        delete params['time'];
        this.searchStatus = params;
        getTableData({ ...params, pageNum: 1, pageSize: this.pageSize });
    };
    renderModalData = () => {
        const { modalData } = this.state;
        let ele;
        if(!modalData) {
            ele = null;
        }
        if(typeof modalData === 'string') {
            ele = (
                <Card title={''}>
                    <div>
                        被拒原因: {modalData}
                    </div>
                </Card>
            );

        } else {
            ele = <CommonTable
                title={() => <div>被拒类型:同盾</div>}
                columns={this.modalTableColumns}
                dataSource={modalData}
            />;
        }
        return (
            <div className={styles.modalWrapper}>{ele}</div>
        );

    }

    //关闭详情modal
    detailModalCancel = () => {
        const { changeDetailModal } = this.props;
        changeDetailModal(false);
    }
    showDetailModal = (record) => {
        const { getOrderDetailData } = this.props;
        const { id } = record;
        getOrderDetailData({ orderId: id });
    }

    orderProcess = (record) => {
        const { id } = record;
        const data = {orderId: id}
        axios({
            url: '/hs/admin/order/getOrderProcess',
            method: 'post',
            data: data
        }).then((res) => {
            // console.log(res);
            if(res.code === 200){  
                this.setState({
                    orderProcessVisible: true,
                    orderProcessInfo: res.data
                })
            }
        })
    }

    orderProcessCancel = () => {
        this.setState({
            orderProcessVisible: false,
        })
    }

    reviewProcessCancel = () => {
        this.setState({
            reviewProcessVisible: false,
        })
    }

    reviewProcess = (record) => {
        const { id } = record;
        const data = {orderId: id}
        axios({
            url: '/hs/admin/order/getOrderReviewProcess',
            method: 'post',
            data: data
        }).then((res) => {
            // console.log(res);
            if(res.code === 200){  
                this.setState({
                    reviewProcessVisible: true,
                    reviewProcessInfo: res.data
                })
            }
        })
    }

    //导出订单
    exportOrder = () => {
        this.setState({btnDisabled: true});
        let hide = message.loading('正在导出', 0);
        const _this = this;
        axios({
            url: '/hs/admin/order/download',
            method: 'post',
            responseType: 'blob',
            data: _this.searchStatus
        }).then((res) => {
            hide && hide();
            this.setState({btnDisabled: false});
            download(res, `订单列表${Date.now()}.xls`);
        }).catch(() => {
            hide && hide();
            this.setState({btnDisabled: false});
        });
    }


    authModalCancel = () => {
        const { changeAuthModal } = this.props;
        changeAuthModal(false);
    }
    authAfterClose = () => {
        this.currentRecord = null;
    }
    handleReset = () => {
        const { userId } = this.currentRecord;
        const { resetOperator } = this.props;
        resetOperator({ userId });
    }

    componentDidMount() {
        const {getTableData} = this.props;
        getTableData({pageNum: 1, pageSize: this.pageSize,...this.searchStatus});
    }

    componentWillUnmount() {
        const {setTableData} = this.props;
        setTableData({
            data: [],
            pagination: {}
        });
    }
    render() {
        const { tableData: {data, pagination}, loading, info, detailVisible, authVisible, authData } = this.props;
        const { visible, btnDisabled, orderProcessVisible, orderProcessInfo, reviewProcessVisible, reviewProcessInfo } = this.state;
        return (
            <div>
                <SearchList submit={this.handleSearch}/>
                <div><Button type={'primary'} disabled={btnDisabled} onClick={this.exportOrder}>导出订单</Button></div>
                { /* 获取不到数据展示模板 */}
                <CommonTable
                    loading={loading}
                    dataSource={data}
                    pagination={pagination}
                    handlePageChange={this.handlePageChange}
                    columns={this.columns}
                />
                <Modal
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    width={800}
                    footer={null}
                    visible={visible}
                    title={"详情"}
                >
                    {this.renderModalData()}
                </Modal>
                <DetailModal visible={detailVisible} info={info} handleCancel={this.detailModalCancel}/>
                <OrderProcessModal visible={orderProcessVisible} info={orderProcessInfo} handleCancel={this.orderProcessCancel} />
                <ReviewProcessModal visible={reviewProcessVisible} info={reviewProcessInfo} handleCancel={this.reviewProcessCancel} />
                <AuthModal
                    handleCancel={this.authModalCancel}
                    modalData={authData}
                    afterClose={this.authAfterClose}
                    visible={authVisible}
                    handleCheck={this.manualCheck}
                    handleReset={this.handleReset}
                />
            </div>
        );
    }
}

const mapStateToProps = state => {
    const {windControlCheckState: {orderListState}} = state;
    return {
        tableData: orderListState["data"],
        loading: orderListState["loading"],
        detailVisible: orderListState['detailVisible'],
        info: orderListState['info'],
        authData: orderListState['authData'],
        authVisible: orderListState['authVisible']
    };
};
const mapDispatchToProps = dispatch => {
    return bindActionCreators(
        {
            getTableData: orderListAction.orlGetTableData,
            setTableData: orderListAction.orlSetTableData,
            getOrderDetailData: orderListAction.orlGetOrderDetail,
            changeDetailModal: orderListAction.orlChangeDetailModal,
            getAuthData: orderListAction.orlGetAuthData,
            changeAuthModal: orderListAction.orlChangeAuthModal,
            resetOperator: orderListAction.orlResetOperator
        },
        dispatch
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(OrderList);
